import type { BaiduElements } from '../../../../../../types/constants'
import type { ThemeType } from '../../../../../../types/interfaces'
import { SearchThemeService } from '../../../../../../lib/abstract'
import { PageHandler } from '../../../../../../lib/page_handler'
import {
  BAIDU_RESULT_BASE_SELECTOR,
  BaiduPageType,
} from '../../../../../../lib/page_handler/platform/baidu/types'
import {
  UNDEFINED_PAGE_TYPE,
  UNDEFINED_PAGE_TYPE_TIPS,
} from '../../../../../../lib/page_handler/type'
import { BODY_SELECTOR, logger, loggerDeduplicator, PLATFORM_PAGE_TYPES, PROJECT_PREFIX, SUPPORTED_PLATFORMS } from '../../../../../../types/constants'
import { BaiduIndexPage } from './baidu/page'
import { BaiduNotFoundPage } from './baidu/page/404'
import { BaiduAdvancedPage } from './baidu/page/advanced'
import { BaiduCommonPage } from './baidu/page/common'
import { BaiduMorePage } from './baidu/page/more'
import { BaiduNewsPage } from './baidu/page/news'
import { BaiduNotePage } from './baidu/page/note'
import { BaiduVideoPage } from './baidu/page/video'
import { BaiduWebPage } from './baidu/page/web'

/**
 * 页面处理器
 */
const PAGE_HANDLERS: Partial<Record<BaiduPageType, any>> = {
  [BaiduPageType.Index]: BaiduIndexPage,
  [BaiduPageType.Web]: BaiduWebPage,
  [BaiduPageType.News]: BaiduNewsPage,
  [BaiduPageType.Video]: BaiduVideoPage,
  [BaiduPageType.Note]: BaiduNotePage,
  [BaiduPageType.More]: BaiduMorePage,
  [BaiduPageType.Advanced]: BaiduAdvancedPage,
  [BaiduPageType.NotFound]: BaiduNotFoundPage,
}

/**
 * 主题服务测试链接 （支持网页、资讯、视频、笔记）
 * 【测试关键词】
 * 1）技术类：python、ubuntu、测试、pycharm、csdn、Ubuntu 安装 MYSQL
 * 2）音乐类：泡沫、邓紫棋
 * 3）视频类：功夫
 * 4）美食类：麻婆豆腐
 * 5）热门类：抖音、Trae、豆包
 * 6）AI 回答：bootstrap5、MAC Big Sur搭建hadoop+spark环境
 * 7）其他：北京去上海、北京天气、重庆旅游攻略
 */
export class BaiduThemeService extends SearchThemeService {
  readonly name: string = 'BaiduTheme'
  readonly platformPageType: string = PLATFORM_PAGE_TYPES.SEARCH.value
  private static instance: BaiduThemeService
  declare readonly elements: BaiduElements
  private readonly commonPage: BaiduCommonPage = BaiduCommonPage.getInstance()
  private readonly pageHandler: PageHandler = PageHandler.getInstance()

  private currentPageType: BaiduPageType | 'default' = this.pageHandler.pages.baidu.pageType
  readonly wrapperSelector: string = BODY_SELECTOR

  constructor() {
    super(SUPPORTED_PLATFORMS.BAI_DU)

    this.updateElementStylesForTheme()
    this.checkPageType(this.currentPageType)
  }

  /**
   * 获取单例实例
   */
  static getInstance(): BaiduThemeService {
    if (!BaiduThemeService.instance) {
      BaiduThemeService.instance = new BaiduThemeService()
    }
    return BaiduThemeService.instance
  }

  /**
   * 批量初始化页面样式
   */
  updateElementStylesForTheme(): void {
    // 通用样式初始化
    this.commonPage.init()

    // 动态获取当前页面处理器并初始化
    const PageHandlerClass = PAGE_HANDLERS[this.currentPageType as BaiduPageType]
    if (PageHandlerClass) {
      PageHandlerClass.getInstance().init()
    }
    else if (this.currentPageType === UNDEFINED_PAGE_TYPE) {
      loggerDeduplicator.warn(UNDEFINED_PAGE_TYPE_TIPS)
    }
    else {
      logger.warn(`未找到 ${this.currentPageType} 页面的处理器`)
    }
  }

  platformStyleVar(theme: ThemeType): string {
    return `
  --${PROJECT_PREFIX}-theme-result-border-primary: ${this.getColorValue(theme, 'resultBorderPrimary')};
  --${PROJECT_PREFIX}-theme-result-border-primary-hover: ${this.getColorValue(theme, 'resultBorderPrimaryHover')};
  `
  }

  getBaseStyles(_theme: ThemeType): string {
    return `
${super.getBaseStyles(_theme)}
`
  }

  getPageStyles(_theme: ThemeType): string {
    return `
${BODY_SELECTOR} {
  background-color: var(${this.themeVarService.search.default.background}) !important;
}
`
  }

  getMainStyles(theme: ThemeType): string {
    // 1. 通用样式
    let commonStyles = this.commonPage.getMainStyles()
    const notSupportedPages: BaiduPageType[] = [
      BaiduPageType.Advanced,
      BaiduPageType.NotFound,
    ]

    if (notSupportedPages.includes(this.currentPageType as BaiduPageType))
      commonStyles = ''

    // 2. 动态获取当前页面样式
    let pageStyles = ''
    const PageHandlerClass = PAGE_HANDLERS[this.currentPageType as BaiduPageType]
    if (PageHandlerClass) {
      pageStyles = PageHandlerClass.getInstance().getMainStyles(theme)
    }

    return `
  /* ===================== 【页面】通用样式 ===================== */   
  ${commonStyles}
  /* ===================== 【页面】独立样式 ===================== */
  ${pageStyles}
`
  }

  getPatchedStyles(_theme: ThemeType): string {
    const supportPages = [
      BaiduPageType.Web,
      BaiduPageType.News,
    ]

    return !supportPages.includes(this.currentPageType as BaiduPageType)
      ? ''
      : `
#content_left {
  ${BAIDU_RESULT_BASE_SELECTOR} {
    /* 平台徽章 */
    [class*="title-box"]:has(> h3) {
      [class^="suffix-icon"] {
        margin-bottom: 0 !important;
      }
    }
    /* 标题间距 */
    [class*="title-box"]:has(> h3), h3[class^="news-title"] {
      margin-bottom: 8px !important;
    }
    /* 标题 */
    [class^="title-wrapper"] h3, h3[class^="news-title"], .c-container > h3 {
      align-items: center !important;
      display: inline-flex !important;
      justify-content: space-between !important;
      ${this.stylesService.wordBreak.singleLine}
      
      a[data-module="title"], a[class^="news-title"]  {
        display: inline-block !important;
        ${this.stylesService.wordBreak.singleLine}
      }
      
      > * {
        margin: 0 !important;
      }
      
      .title-icon {
        width: 18px !important;
        height: 18px !important;
        margin-right: 8px !important;
      }
    }
  }
}
`
  }

  getFixedStyles(_theme: ThemeType): string {
    return ``
  }
}
